package com.syni.mdd.sjb.community.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbChatCount;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbUserCount;
import com.syni.mdd.sjb.common.component.mybatis.community.mapper.SjbChatCountMapper;
import com.syni.mdd.sjb.common.component.utils.common.exception.BusinessException;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.community.base.entity.vo.ChatDataCountVO;
import com.syni.mdd.sjb.community.base.entity.vo.ChatRangeCountVO;
import com.syni.mdd.sjb.community.base.service.SjbChatCountService;
import com.syni.mdd.sjb.community.base.utils.MybatisUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wangbaitao
 * @version 1.0.0
 * <h>企业微信用户统计数据实体 service impl</h>
 * @Date 2021/3/3
 **/
@Service
@Transactional
public class SjbChatCountServiceImpl extends ServiceImpl<SjbChatCountMapper, SjbChatCount>
        implements SjbChatCountService {
    /**
     * 获取上一日的群聊统计数据
     *
     * @return 查询结果
     */
    @Override
    public Map<String, Object> getChatCount(String corpId) {
        SjbChatCount sjbUserCount = getOne(new QueryWrapper<SjbChatCount>()
                .eq(SjbChatCount.CORP_ID, corpId).eq(SjbChatCount.STAT_TIME, LocalDate.now().minusDays(1)));
        return ResultMapHelper.success(sjbUserCount, "获取成功", true);
    }

    /**
     * 获取日期区间的统计i数据
     *
     * @param corpId    企业id
     * @param beginDate 开始日期
     * @param endDate   结束日期
     * @return 查询结果
     */
    @Override
    public Map<String, Object> getChatCountByDate(String corpId, String beginDate, String endDate) {
        if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate) || StringUtils.isBlank(corpId)) {
            throw new BusinessException("业务异常：参数不足");
        }
        List<SjbChatCount> chatCounts = list(new QueryWrapper<SjbChatCount>().eq(SjbUserCount.CORP_ID, corpId)
                .between(SjbChatCount.STAT_TIME, MybatisUtils.getBeginDay(beginDate), MybatisUtils.getEndDay(endDate))
                .orderByAsc(SjbChatCount.STAT_TIME));
        ChatDataCountVO chatDataCountVO = new ChatDataCountVO();
        List<ChatRangeCountVO> rangeCountVOS = new ArrayList<>();
        chatCounts.forEach(chatCount -> rangeCountVOS.add(ChatRangeCountVO.builder().statDate(chatCount.getStatTime())
                .count(chatCount.getMsgTotal()).build()));
        chatDataCountVO.setMsgTotal(rangeCountVOS);
        return ResultMapHelper.success(chatDataCountVO, "获取成功", true);
    }
}
